import datetime
import logging
import os
import time
import urlparse

from django.utils import simplejson
from google.appengine.api import users
from google.appengine.api import xmpp
from google.appengine.ext import db
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp

from config import ADMINS
from config import DEBUG
from config import NUM_CHAT_MESSAGES
from config import TEMPLATES
import decorators
import models


_log = logging.getLogger(__name__)


class HomeHandler(webapp.RequestHandler):

    def get(self):
        path = os.path.join(TEMPLATES, 'home.html')
        title = 'Home'
        html = template.render(path, locals(), debug=DEBUG)
        self.response.out.write(html)


class LoginHandler(webapp.RequestHandler):

    @decorators.require_admin
    def get(self):
        self.redirect('/admin')


class BlogHandler(webapp.RequestHandler):

    def get(self):
        path = os.path.join(TEMPLATES, 'blog.html')
        title = "Blog"
        html = template.render(path, locals(), debug=DEBUG)
        self.response.out.write(html)


class LogoutHandler(webapp.RequestHandler):

    def get(self):
        logout_url = users.create_logout_url('/')
        self.redirect(logout_url)


class AdminHandler(webapp.RequestHandler):

    @decorators.require_admin
    def get(self):
        path = os.path.join(TEMPLATES, 'admin.html')
        title = 'Admin'
        html = template.render(path, locals(), debug=DEBUG)
        self.response.out.write(html)


class ResumeHandler(webapp.RequestHandler):

    def get(self):
        path = os.path.join(TEMPLATES, 'resume.html')
        html = template.render(path, locals(), debug=DEBUG)
        self.response.out.write(html)


class VideosHandler(webapp.RequestHandler):

    def get(self):
        path = os.path.join(TEMPLATES, 'videos.html')
        title = 'Videos'

        video_objs = models.Video.all().order('created')
        video_dicts = []
        for video_obj in video_objs:
            question = video_obj.question
            url = video_obj.youtube_url
            parsed = urlparse.urlparse(url)
            params = parsed.query
            params = params.split('&')
            params = dict([p.split('=') for p in params])
            video_id = params['v']
            video_dict = {
                'question': question,
                'id': video_id,
            }
            video_dicts.append(video_dict)

        html = template.render(path, locals(), debug=DEBUG)
        self.response.out.write(html)

    @decorators.require_admin
    def post(self):
        question = self.request.get('question')
        youtube_url = self.request.get('youtube_url')
        video = models.Video(question=question, youtube_url=youtube_url)
        video.put()
        self.redirect('/videos')


class LinksHandler(webapp.RequestHandler):

    def get(self):
        path = os.path.join(TEMPLATES, 'links.html')
        title = 'Links'
        links = models.Link.all().order('created')
        html = template.render(path, locals(), debug=DEBUG)
        self.response.out.write(html)

    @decorators.require_admin
    def post(self):
        title = self.request.get('title')
        description = self.request.get('description')
        url = self.request.get('url')
        link = models.Link(title=title, description=description, url=url)
        link.put()
        self.redirect('/links')


class ChatHandler(webapp.RequestHandler):

    def get(self):
        after = self.request.get('after')

        if after:
            path = os.path.join(TEMPLATES, 'status.html')
            online = False
            for admin in ADMINS:
                if xmpp.get_presence(admin):
                    online = True
                    break
            status = template.render(path, locals(), debug=DEBUG)

            path = os.path.join(TEMPLATES, 'messages.html')
            after = float(after)
            after = datetime.datetime.fromtimestamp(after)
            messages = models.Message.all().filter('created >', after).order('-created')
            now = datetime.datetime.now()
            now = time.mktime(now.timetuple()) + now.microsecond / 1000000.0
            messages = template.render(path, locals(), debug=DEBUG)

            json = {
                'status': status,
                'messages': messages,
            }
            json = simplejson.dumps(json)
            self.response.out.write(json)

        else:
            path = os.path.join(TEMPLATES, 'chat.html')
            title = 'Chat'
            messages = models.Message.all().order('-created').fetch(NUM_CHAT_MESSAGES)
            online = False
            for admin in ADMINS:
                if xmpp.get_presence(admin):
                    online = True
                    break
            now = datetime.datetime.now()
            now = time.mktime(now.timetuple()) + now.microsecond / 1000000.0
            html = template.render(path, locals(), debug=DEBUG)
            self.response.out.write(html)

    def post(self):
        path = os.path.join(TEMPLATES, 'messages.html')
        sender = 'Visitor'
        body = self.request.get('body')
        body = body.split('\n')[0]
        message = models.Message(sender=sender, body=body)
        message.put()
        after = self.request.get('after')
        after = float(after)
        after = datetime.datetime.fromtimestamp(after)
        messages = models.Message.all().filter('created >', after).order('-created')
        now = datetime.datetime.now()
        now = time.mktime(now.timetuple()) + now.microsecond / 1000000.0
        html = template.render(path, locals(), debug=DEBUG)
        self.response.out.write(html)
        xmpp.send_message(ADMINS.keys(), body)

    @decorators.require_admin
    def delete(self):
        messages = models.Message.all()
        db.delete(messages)
        self.redirect('/chat')


class GoogleTalkHandler(webapp.RequestHandler):

    def post(self):
        im = xmpp.Message(self.request.POST)
        sender = im.sender.split('/', 1)[0].lower()
        if sender in ADMINS:
            sender = ADMINS[sender]
            body = im.body
            message = models.Message(sender=sender, body=body)
            message.put()
